import { FileUtils, TFileUtils } from "./fileutils";
import { CDNClientConfigs } from "./CDNConfigs";
import { UploadUtils } from "./TCDNUploadFlowPorts";
import fs from "fs"
import yaml from "yaml"

class UploadEGBLU3d {
    configs: CDNClientConfigs = {
        test: {
            cdnHost: "S3",
            accessKeyId: "",
            secretAccessKey: '',
            region: "",
            bucket: "",
            downloadUrl: "",
            downloadPath: "",
            allowOverwirte: true,
        },
        pretest: {
            cdnHost: "S3",
            accessKeyId: "",
            secretAccessKey: '',
            region: "",
            bucket: "",
            downloadUrl: "",
            downloadPath: "",
            allowOverwirte: false,
        },
        release: {
            cdnHost: "S3",
            accessKeyId: "",
            secretAccessKey: '',
            region: "",
            bucket: "",
            downloadUrl: "",
            downloadPath: "",
            allowOverwirte: false,
        },
    }

    parseCDNConfig(cdnConfigPath: string) {
        try {
            let content = fs.readFileSync(cdnConfigPath, "utf-8")
            console.log(`cdnUploadConfig-content: ${JSON.stringify(content)}`)
            let lines = content.split(/(?:\r?\n|\r)/g)
            // 简单跳过tag处理
            let startPos = lines.findIndex(line => line == "MonoBehaviour:")
            let newContent = lines.slice(startPos).join("\n")
            var obj = yaml.parse(newContent)
            let objs = obj["MonoBehaviour"] as CDNClientConfigs
            console.log("parsedConfig: " + JSON.stringify(objs))
            this.configs = objs
        } catch (ex) {
            console.error(`解析cdn上传配置失败: ${cdnConfigPath}`)
            console.error(ex)
        }
    }

    protected uploadAssets = async () => {
        let buildOptions = UploadUtils.buildOptions
        await UploadUtils.uploadPlatformRes({
            outputName: `${buildOptions.outputName}`,
            platform: buildOptions.platform,
            releasePlatform: buildOptions.releasePlatform,
            prefix: buildOptions.prefix,
        })
        await UploadUtils.displayUrl()
        await UploadUtils.removeRemoteFolders()
    }

    /**
     * 上传微信小游戏需要的分包资源
     */
    protected uploadWechatgameGamePart2 = async () => {
        let buildOptions = UploadUtils.buildOptions
        let releasePlatform = buildOptions.platform
        let prefix = buildOptions.prefix;
        if (prefix == null) {
            prefix = "";
        }
        if (releasePlatform == "WebGL") {
            // 上传路径必须与微信小游戏转换工具里规定的CDN url前缀一致
            await UploadUtils.upload(`${UploadUtils.targetDir}`, ".", releasePlatform, prefix)
        }
    }

    protected _upload = async () => {
        await FileUtils.execAsyncOn(UploadUtils.targetDir, async () => {
            UploadUtils.localUploadDir = ".."
            await this.uploadAssets()
        })
    }

    upload = async () => {
        UploadUtils.setWithConfigs(this.configs)
        console.log("UploadUtils:", UploadUtils);
        await this._upload()
    }

    async uploadWechatGame() {
        UploadUtils.setWithConfigs(this.configs)
        console.log("UploadUtils:", UploadUtils);

        await FileUtils.execAsyncOn("./", async () => {
            await this.uploadWechatgameGamePart2();
        })
    }

    async uploadSingleFile(localPath: string, remotePath: string) {
        UploadUtils.setWithConfigs(this.configs)
        console.log("UploadUtils:", UploadUtils);
        console.log(`uploadSingleFile: ${localPath} -> ${remotePath}`);

        await UploadUtils.uploadFile(localPath, remotePath);
    }

    fetchAndAddVersionCode = async (autoSave: boolean) => {
        try {
            UploadUtils.setWithConfigs(this.configs)
            console.log("UploadUtils:", UploadUtils);
            await FileUtils.execAsyncOn(UploadUtils.targetDir, async () => {
                var outVersionCode = await UploadUtils.fetchAndAddVersionCode(autoSave)
                console.error(`outVersionCode:${outVersionCode}`);
            })
        } catch (e) {
            console.error(e)
        }
    }

    setUploadDefaultConfig() {
        UploadUtils.setWithConfigs(this.configs)
    }


}

export const UploadAbilityEGBLU3D = new UploadEGBLU3d();
